package com.zyx.concurrentdemo.mytest.c04;

import java.util.concurrent.locks.LockSupport;

/**
 * @author zyx
 * @since 2021/10/16 19:15
 * desc: 基于park和unpark实现数据的顺序打印
 */
public class OrderingPrintDemo02 {

    public static Thread t1, t2, t3;

    public static void main(String[] args) {
        ParkAndUnpark parkAndUnpark = new ParkAndUnpark(5);

        t1 = new Thread(() -> parkAndUnpark.run("a", t2), "t1");
        t2 = new Thread(() -> parkAndUnpark.run("b", t3), "t2");
        t3 = new Thread(() -> parkAndUnpark.run("c", t1), "t3");

        t1.start();
        t2.start();
        t3.start();

        LockSupport.unpark(t1);
    }
}

class ParkAndUnpark {
    /**
     * 循环次数
     */
    private final int loopNumber;

    public ParkAndUnpark(int loopNumber) {
        this.loopNumber = loopNumber;
    }

    public void run(String msg, Thread nextThread) {
        for (int i = 0; i < this.loopNumber; i++) {
            System.out.print(msg);
            // 暂停当前线程
            LockSupport.park();
            // 恢复nextThread线程
            LockSupport.unpark(nextThread);
        }
    }
}
